//
//  MallViewController.m
//  ShouYi
//
//  Created by yrapp on 16/3/8.
//  Copyright © 2016年 yurui. All rights reserved.
//

#import "MallViewController.h"
#import "MallHeaderView.h"
#import "HdListModel.h"

#import "MallCollectionReusableView.h"
#import "MallCollectionViewCell.h"
#import "MallTwoCollectionReusableView.h"

//商品详情页
#import "ShopDetailViewController.h"
//购物车
#import "CartTableViewController.h"
//分类页面
#import "MallClassViewController.h"

@interface MallViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
//商品collection
@property(nonatomic,strong)UICollectionView *collectionView;

//列表collection
@property(nonatomic,strong)MallHeaderView *headerView;

@property(nonatomic,strong)NSMutableArray *lunboArray;

@property(nonatomic,strong)NSMutableArray *listArray;

@property(nonatomic,strong)NSMutableArray *proListArray;


@end

@implementation MallViewController


- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBarHidden = NO;

}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kViewBackColor;
    
    self.navigationController.navigationBar.barTintColor = kBackGroundColor;
    // Do any additional setup after loading the view.
    
    [self addNavigationBar];
    
    
    
    [self addItems];
    //解析轮播图
    [self updataForHdlist];
    //解析主界面商品展示
    [self updataForMainlist];
}

//添加头部搜搜索框
- (void)addNavigationBar {
    
    UIView *navigationView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 210/312.0 * kWidth, 25)];
    navigationView.backgroundColor = [UIColor whiteColor];
    self.navigationItem.titleView = navigationView;
    
    UIButton *gouwuButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    gouwuButton.frame = CGRectMake(0, 0, 25, 25);
    [gouwuButton setImage:[UIImage imageNamed:@"icon_sy_gouwuche"] forState:(UIControlStateNormal)];
    [gouwuButton addTarget:self action:@selector(toCartVC) forControlEvents:(UIControlEventTouchUpInside)];
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithCustomView:gouwuButton];
    self.navigationItem.rightBarButtonItem = rightButton;
}

//购物车按钮
- (void)toCartVC {
    self.hidesBottomBarWhenPushed = YES;
    CartTableViewController *CartVC = [[CartTableViewController alloc] init];
    [self.navigationController pushViewController:CartVC animated:YES];
    self.hidesBottomBarWhenPushed = NO;
    
}
//添加集合视图
- (void)addItems {
    
    // 创建一个布局对象
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    // 设置集合视图行间距
    layout.minimumLineSpacing = 13;
    //设置集合视图 每个item之间的间隔
    layout.minimumInteritemSpacing = 12;
    
    //设置集合视图中每个item的大小
    layout.itemSize = CGSizeMake((kWidth - 36) / 2, kWidth/ 2 + 20);
    
    // 创建一个集合视图
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0,0, kWidth, kHeight + 64) collectionViewLayout:layout];
    
    //self.collectionView.
    self.collectionView.contentInset = UIEdgeInsetsMake(0, 12, 0, 12);
    
    self.collectionView.backgroundColor = [UIColor colorWithRed:236.0/255 green:240.0/255 blue:242.0/255 alpha:1];
    
    // 指定集合视图的数据源
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    
    //注册cell
    [self.collectionView registerClass:[MallCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    
    [self.collectionView registerClass:[MallCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    [self.collectionView registerClass:[MallTwoCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"twoHeader"];
    [self.view addSubview:self.collectionView];
    
   //添加加载刷新
    [self AddMJrefresh];
    
}
#pragma mark --- 数据处理 ---
//添加上拉刷新下拉加载
//刷新 下拉加载
- (void)AddMJrefresh {
    self.collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        NSLog(@"下拉加载");
        [self.collectionView.mj_footer endRefreshing];
    }];
    
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        NSLog(@"上拉刷新");
        [self.collectionView.mj_header endRefreshing];
    }];
}
//商品列表
- (void)updataForMainlist {
    
    
    NSString *cuuid = [[NSUserDefaults standardUserDefaults] objectForKey:@"CFUUID"];
    NSString *url = [KMainList stringByAppendingString:[NSString stringWithFormat:@"&uuid=%@",cuuid]];
    
    [LORequestManger GET:url success:^(id response) {
        NSArray *array = (NSArray *)response;
        
        for (NSDictionary *dic in array) {
            prolistModel *model = [prolistModel setUpdateDic:dic];
            [self.proListArray addObject:model];
        }
        
        [self.collectionView reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
    
}

//轮播图
- (void)updataForHdlist {
    
    NSString *cuid = [[NSUserDefaults standardUserDefaults] objectForKey:@"CFUUID"];
    NSString *url = [KHdlist stringByAppendingString:[NSString stringWithFormat:@"&uuid=%@",cuid]];
    
    
    [LORequestManger GET:url success:^(id response) {
        
        self.lunboArray = nil;
        
        NSArray *dic = (NSArray *)response;
        for (NSDictionary *HdList in dic) {
            HdListModel *model = [HdListModel setUpdateDic:HdList];
            [self.lunboArray addObject:model];
        }
        [self.collectionView reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
}

//懒加载
- (NSMutableArray *)lunboArray {
    
    if (!_lunboArray) {
        _lunboArray = [NSMutableArray array];
    }
    return _lunboArray;
    
}

- (NSMutableArray *)proListArray {
    if (!_proListArray) {
        _proListArray = [NSMutableArray array];
    }
    return _proListArray;
}

#pragma mark --- collectionView ---
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.proListArray.count;
}


- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    
    return 1;
    
    
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    MallCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    [cell.addButton addTarget:self action:@selector(cellButton:) forControlEvents:(UIControlEventTouchUpInside)];
    cell.addButton.tag = indexPath.row + 2000;
    prolistModel *model = self.proListArray[indexPath.row];
    
    [cell setModel:model];
    
    return cell;
    
    
}

- (void)cellButton:(UIButton *)button {
    
    [button setImage:[UIImage imageNamed:@"卖已选"] forState:(UIControlStateNormal)];
    NSLog(@"这个button的tag是: %ld",(long)button.tag);
    
    
    
    
    
}

//collectionView 的 headerView
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    
    if (collectionView == self.collectionView) {
        
        if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
            
            if (indexPath.section == 0) {
                
                MallCollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
                view.backgroundColor = [UIColor whiteColor];
                NSArray *array = view.subviews;
                
                NSLog(@"%lu",(unsigned long)array.count);
                
                if (array.count == 0) {
                    
                    NSLog(@"count %lu",(unsigned long)self.lunboArray.count);
                    
                    if (self.lunboArray.count > 0) {
                        
                        _headerView = [[MallHeaderView alloc] initWithFrame:CGRectMake(-12, 0, kWidth, kHeight / 4.0+ 157) imageArray:_lunboArray delegate:self action:nil timer:4.00 selector:nil];
                        _headerView.backgroundColor = [UIColor whiteColor];
                        [_headerView.xinButton addTarget:self action:@selector(classButton:) forControlEvents:(UIControlEventTouchUpInside)];
                        [_headerView.hotButton addTarget:self action:@selector(classButton:) forControlEvents:(UIControlEventTouchUpInside)];
                        [_headerView.cuButton addTarget:self action:@selector(classButton:) forControlEvents:(UIControlEventTouchUpInside)];
                        [_headerView.teButton addTarget:self action:@selector(classButton:) forControlEvents:(UIControlEventTouchUpInside)];
                        
                        [_headerView.xin2Button addTarget:self action:@selector(classButton:) forControlEvents:(UIControlEventTouchUpInside)];
                        [_headerView.hot2Button addTarget:self action:@selector(classButton:) forControlEvents:(UIControlEventTouchUpInside)];
                        [_headerView.cu2Button addTarget:self action:@selector(classButton:) forControlEvents:(UIControlEventTouchUpInside)];
                        [_headerView.te2Button addTarget:self action:@selector(classButton:) forControlEvents:(UIControlEventTouchUpInside)];
                        
                        [view addSubview:_headerView];
                    }
                }
                
                return view;
                
            } else if (indexPath.section == 1 || indexPath.section == 2){
                
                MallTwoCollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"twoHeader" forIndexPath:indexPath];
                
                if (indexPath.section == 1) {
                    [view.headerImage setImage:[UIImage imageNamed:@"zhuangshi2.jpg"] forState:(UIControlStateNormal)];
                }else {
                    [view.headerImage setImage:[UIImage imageNamed:@"zhuangshi1.jpg"] forState:(UIControlStateNormal)];
                }
                
                return view;
                
            }
            
            
        }
    }
    
    
    return nil;
}


//headerView 高度
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    if (collectionView == self.collectionView) {
        
        if (section == 0) {
            
            return CGSizeMake(kWidth, kHeight / 4.0+ 157);
        }else {
            return CGSizeMake(kWidth, 40);
        }
    }
    
    return CGSizeMake(0,0);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    self.hidesBottomBarWhenPushed = YES;
    ShopDetailViewController *shopDVC = [[ShopDetailViewController alloc] init];
    prolistModel *model = self.proListArray[indexPath.row];
    shopDVC.proModel = model;
    [self.navigationController pushViewController:shopDVC animated:YES];
    self.hidesBottomBarWhenPushed = NO;
    
}


- (void)classButton:(UIButton *)button {
    
    NSLog(@"12");
    
    MallClassViewController *mallClassVC = [[MallClassViewController alloc] init];
    [self.navigationController pushViewController:mallClassVC animated:YES];
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
